import 'dart:async';
import 'package:enjoy_three/utils/eventbus.dart';
import 'package:enjoy_three/utils/http.dart';
import 'package:enjoy_three/utils/toast.dart';
import 'package:enjoy_three/utils/token.dart';
import 'package:flutter/material.dart';


class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //倒计时
  int _countdown = 60;
  bool _isCountingDown = false;
  Timer? _timer; // 定义 Timer 类型变量

  @override
  void dispose() {
   // 在组件销毁时取消定时器
   _timer?.cancel();
    super.dispose();
  }
//开始倒计时
  void _startCountdown() {
    if (_isCountingDown) {
      return;
    }
    _isCountingDown = true;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isCountingDown = false;
          _countdown = 60;
          timer.cancel(); // 倒计时结束后取消定时器
        }
      });
    });
  }
//手机号验证
final TextEditingController _phoneController = TextEditingController();
final TextEditingController _codeController = TextEditingController();

//验证手机格式
void _getVerificationCode () async {
  if(_phoneController.text.isEmpty){
    return ToastUtil.showInfo('请输入手机号');
  }
  RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
  if(!regExp.hasMatch(_phoneController.text)){
    return ToastUtil.showInfo('请输入正确的手机号');
  }

  var res = await http.get('/code',params: {
    'mobile': _phoneController.text
  });
  if(res['code'] != 10000) return ToastUtil.showInfo('获取验证码失败');
  ToastUtil.showInfo('验证码发送成功');

  Future.delayed(const Duration(seconds: 2),(){
    _codeController.text = res['data']['code'];
  });

  _startCountdown();

}

//提交信息
void _submit() async {
  if(_phoneController.text.isEmpty){
    return ToastUtil.showInfo('请输入手机号');
  }
  RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
  if(!regExp.hasMatch(_phoneController.text)){
    return ToastUtil.showInfo('请输入正确的手机号');
  }
  if(_codeController.text.isEmpty){
    return ToastUtil.showInfo('请输入验证码');
  }
  if(_codeController.text.length != 6){
    return ToastUtil.showInfo('请输入6位验证码');
  }
  RegExp regExp2 =RegExp(r'^\d{6}$');
  if(!regExp2.hasMatch(_codeController.text)){
    return ToastUtil.showInfo('验证码错误');
  }

  //调用登录接口
    //发起请求
    var res= await http.post('/login',{
      'mobile': _phoneController.text,
      'code': _codeController.text
    });
    if(res['code']!=10000) return ToastUtil.showError('登录失败');
    //存token
    TokenManager().saveToken(res['data']['token']);
    ToastUtil.showSuccess('登录成功');
  //存出token
  TokenManager().saveToken(res['data']['token']);
  _timer?.cancel();
  Navigator.pop(context);

//刷新token
eventBus.fire(refreshMine());
}





  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Row(
                children: [
                  Text('登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold))
                ],
              ),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))
                ],
              ),
              const SizedBox(height: 30),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                   Expanded(
                    child: TextField(
                      //手机号
                      controller: _phoneController,
                      maxLength: 11,
                      keyboardType: TextInputType.phone,
                      style: TextStyle(fontSize: 16),
                      decoration: InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入手机号',
                      ),
                    ),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shadowColor: Colors.transparent,
                      foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                     _getVerificationCode();
                    },
                    child: _isCountingDown ? Text('$_countdown后获取验证码',style: TextStyle(color: Colors.amber),):const Text('获取验证码'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
               TextField(
                //验证码
                controller: _codeController,
                keyboardType: TextInputType.number,
                maxLength: 6,
                style: TextStyle(fontSize: 16),
                decoration: InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
              ),
              const SizedBox(height: 8),
              const Row(children: [
                Text('未注册手机号经验证后将自动登录', style: TextStyle(fontSize: 12, color: Colors.grey)),
              ]),
              const SizedBox(height: 50),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                        minimumSize: const Size(100, 50),
                      ),
                      onPressed: () {
                        _submit();
                      },
                      child: const Text('登录', style: TextStyle(color: Colors.white, fontSize: 20)),
                    )
                  )
                ]
              )
            ])));
  }
}